<template>
	<div class="w-full">
		<el-form :inline="true" :model="formInline">
			<el-form-item label="语义类别">
				<el-input
					v-model="formInline.title"
					placeholder="语义类别"
					clearable
				></el-input>
			</el-form-item>
			<el-form-item label="关键词">
				<el-input
					v-model="formInline.keyword_mes"
					placeholder="关键词"
					clearable
				></el-input>
			</el-form-item>
			<el-form-item>
				<el-button
					type="primary"
					@click="
						renderData();
						ElMessage.success('查询成功');
					"
					>查询</el-button
				>
				<el-button type="success" @click="resetForm()">新增</el-button
				><el-button
					type="danger"
					@click="
						dataListSelections.length <= 0
							? ElMessage.warning('请至少选中一行')
							: deleteHandle()
					"
					>批量删除</el-button
				>
			</el-form-item>
		</el-form>
		<el-table
			:data="tableData"
			stripe
			style="width: 100%"
			@selection-change="selectionChangeHandle"
		>
			<el-table-column
				type="selection"
				header-align="center"
				align="center"
				width="50"
			>
			</el-table-column>
			<el-table-column fixed prop="title" label="语义类别" width="100">
			</el-table-column>
			<el-table-column prop="sentence_nub" label="类别语句数" width="100">
			</el-table-column>
			<el-table-column prop="types" label="关键词（数量/条）">
				<template #default="scope">
					<span>{{ filterTypes(scope.row.types) }}</span>
				</template>
			</el-table-column>
			<el-table-column fixed="right" label="操作" width="140">
				<template #default="scope">
					<el-button link type="primary" size="small" @click="detail(scope.row)"
						>详情</el-button
					>
					<el-button
						link
						type="warning"
						size="small"
						@click="save(scope.row.type_id, scope.row.title)"
						>修改</el-button
					>
					<el-button
						link
						type="danger"
						size="small"
						@click="deleteHandle(scope.row.type_id)"
						>删除</el-button
					>
				</template>
			</el-table-column>
		</el-table>
		<el-affix position="bottom" :offset="60" class="mt-4">
			<el-pagination
				class="mt-2"
				size="small"
				v-model:current-page="formInline.current"
				v-model:page-size="formInline.size"
				:page-sizes="[15, 20, 50, 100]"
				:background="true"
				layout="total, sizes, prev, pager, next, jumper"
				:total="total"
				@size-change="renderData"
				@current-change="renderData"
			/>
		</el-affix>
	</div>
	<el-dialog
		title="添加语义分类"
		v-model="dialogFormVisible"
		:width="dialogWidth"
	>
		<el-form :model="formDialog" label-position="top">
			<el-form-item label="关键词列表">
				<el-tag
					:key="tag"
					v-for="tag in formDialog.keywordTypeMessages"
					closable
					:disable-transitions="false"
					@close="handleClose(tag.keyword_mes + '#' + tag.answer)"
				>
					{{ tag.keyword_mes + "#" + tag.answer }}
				</el-tag>
			</el-form-item>
			<el-form-item label="语句分类">
				<el-input v-model="formDialog.title"></el-input>
			</el-form-item>
			<el-form-item label="关键词">
				<el-col :span="16">
					<el-input v-model="inputValue"></el-input>
				</el-col>
				<el-col :span="1"></el-col>
				<el-col :span="3">
					<el-button type="primary" @click="handleInputConfirm">添加</el-button>
				</el-col>
			</el-form-item>
			<el-form-item label="缺失回复">
				<el-input type="textarea" v-model="formDialog.answer"></el-input>
			</el-form-item>
		</el-form>

		<template #footer>
			<div class="dialog-footer">
				<el-button @click="dialogFormVisible = false">取 消</el-button>
				<el-button type="primary" @click="addData">确 定</el-button>
			</div>
		</template>
	</el-dialog>

	<el-dialog
		v-model="dialogTableVisible"
		title="关键词列表"
		:width="dialogTableWidth"
		@close="closeKt()"
	>
		<el-form :inline="true">
			<el-form-item>
				<el-button type="success" @click="selectTree()">新增</el-button>
			</el-form-item>
		</el-form>
		<el-table :data="gridData" style="width: 100%" stripe>
			<el-table-column fixed property="type_id" label="语句id" width="70">
			</el-table-column>
			<el-table-column property="keyword_type_id" label="关键词id" width="80">
			</el-table-column>
			<el-table-column
				property="keyword_mes"
				label="关键词（标注量）"
				width="140"
			>
				<template #default="scope">
					<span>{{ scope.row.keyword_mes }}({{ scope.row.type_number }})</span>
				</template>
			</el-table-column>
			<el-table-column property="answer" label="缺失回复" />
			<el-table-column fixed="right" label="操作" width="100">
				<template #default="scope">
					<el-button
						link
						type="warning"
						size="small"
						@click="selectTree(scope.row)"
						>修改</el-button
					>
					<el-button
						link
						type="danger"
						size="small"
						@click="deleteKt(scope.row.keyword_type_id)"
						>删除</el-button
					>
				</template>
			</el-table-column>
		</el-table>
		<el-dialog title="添加关键词" v-model="ktModelVisible" :width="dialogWidth">
			<el-form :model="ktModel" label-position="top">
				<el-form-item label="语句分类">
					<el-select
						v-model="selectValue"
						value-key="type_id"
						style="width: 100%"
					>
						<el-option
							v-for="item in options"
							:key="item.type_id"
							:label="item.title"
							:value="item"
						>
							<span style="float: left">{{ item.title }}</span>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="关键词">
					<el-input v-model="ktModel.keyword_mes"></el-input>
				</el-form-item>
				<el-form-item label="缺失回复">
					<el-input type="textarea" v-model="ktModel.answer"></el-input>
				</el-form-item>
			</el-form>

			<template #footer>
				<div class="dialog-footer">
					<el-button @click="ktModelVisible = false">取 消</el-button>
					<el-button type="primary" @click="saveKt()">确 定</el-button>
				</div>
			</template>
		</el-dialog>
	</el-dialog>
</template>
<script setup lang="ts">
	useHead({
		title: "语义分类管理",
	});

	const current = ref(1);
	const size = ref(15);
	const total = ref(0);
	const formInline = ref({
		current: current.value,
		size: size.value,
		title: "",
		keyword_mes: "",
	});

	const formDialog = reactive({
		title: "",
		keywordTypeMessages: [],
		answer: "",
	});

	const dialogFormVisible = ref(false);
	const dialogTableVisible = ref(false);
	const inputValue = ref(undefined);
	const tableData = ref([]);
	const gridData = ref([]);
	const dataListSelections = ref([]);
	const resetForm = () => {
		formDialog.title = "";
		formDialog.keywordTypeMessages = [];
		formDialog.answer = "";
		inputValue.value = "";
		dialogFormVisible.value = true;
	};
	const filterTypes = (types) => {
		let meses = types
			.filter((t) => t.keyword_type_id != 0 && t.keyword_type_id != null)
			.map((item) => {
				return item.keyword_mes;
			});
		if (meses.length > 0) {
			return meses.join(",") + "(" + meses.length + ")";
		}
		return "";
	};

	const handleClose = (tag) => {
		let tags = formDialog.keywordTypeMessages;
		for (var i = 0; i < tags.length; i++) {
			let t = tags[i];
			if (t.keyword_mes + "#" + t.answer == tag) {
				formDialog.keywordTypeMessages.splice(i, 1);
			}
		}
	};

	const handleInputConfirm = () => {
		let input = inputValue.value;
		if (!formDialog.answer || !input) {
			ElMessage.error("请输入关键词和缺失回复");
			return;
		}
		if (input) {
			let tag = { keyword_mes: input, answer: formDialog.answer };
			formDialog.keywordTypeMessages.push(tag);
		}
	};
	const selectionChangeHandle = (val) => {
		dataListSelections.value = val;
	};
	const dialogWidth = ref("300px");
	const dialogTableWidth = ref("300px");
	onMounted(() => {
		renderData();
		window.addEventListener("resize", resizeWindow(dialogWidth));
		window.addEventListener("resize", resizeTable(dialogTableWidth));
	});
	//渲染
	const renderData = () => {
		pageTree(formInline.value).then((res) => {
			tableData.value = [];
			if (res.value.error === 0) {
				current.value = res.value.data.current;
				total.value = res.value.data.total;
				tableData.value = res.value.data.records;
			}
		});
	};
	// 删除
	const deleteHandle = (id) => {
		var ids = id
			? [id]
			: dataListSelections.value.map((item) => {
					return item.type_id;
			  });
		ElMessageBox.confirm(
			`确定对[id=${ids.join(",")}]进行[${id ? "删除" : "批量删除"}]操作?`,
			"提示",
			{
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			}
		).then(() => {
			deleteTree(ids).then(async (res) => {
				if (res.value.error === 0) {
					ElMessage.success("删除成功");
					renderData();
				} else {
					ElMessage.error("删除失败");
				}
			});
		});
	};

	const save = (id, title) => {
		ElMessageBox.prompt("语句分类", "修改语句分类", {
			confirmButtonText: "确定",
			cancelButtonText: "取消",
			inputValue: title,
		})
			.then(({ value }) => {
				if (value) {
					saveTree({
						type_id: id,
						title: value,
					}).then((res) => {
						if (res.value.error === 0) {
							ElMessage({
								type: "success",
								message: "修改成功",
							});
							renderData();
						}
					});
				}
			})
			.catch(() => {
				ElMessage({
					type: "info",
					message: "取消编辑",
				});
			});
	};
	const addData = () => {
		if (formDialog.title === "") {
			ElMessage.error("请输入语句分类！");
			return;
		}
		addSentenceType(formDialog).then(async (res) => {
			if (res.value.error === 0) {
				renderData();
				dialogFormVisible.value = false;
				ElMessage.success("新增成功");
			}
		});
	};

	//关键词管理
	const type_id = ref("");
	const keyword_type_id = ref("");
	const ktModelVisible = ref(false);
	const ktDialog = {
		title: "",
		type_id: "",
		keyword_type_id: "",
		keyword_mes: "",
		answer: "",
	};
	const ktModel = reactive({ ...ktDialog });
	type Option = {
		title: string;
		type_id: string;
	};
	const selectValue = ref<Option>();
	const options = ref([]);
	const selectTree = (row) => {
		let typeId = row?.type_id;
		let keywordTypeId = row?.keyword_type_id;
		ktModelVisible.value = true;
		keyword_type_id.value = keywordTypeId;
		ktModel.keyword_mes = row?.keyword_mes;
		ktModel.answer = row?.answer;
		if (!typeId) {
			//重置
			Object.assign(ktModel, ktDialog);
		}
		listTree().then((res) => {
			options.value = [];
			if (res.value.error === 0) {
				const { data } = res.value;
				for (var i = 0; i < data.length; i++) {
					let tree = data[i];
					let option = {
						title: tree.title,
						type_id: tree.type_id,
					};
					if (typeId === tree.type_id) {
						selectValue.value = option;
					}
					options.value.push(option);
				}
			}
		});
	};
	const detail = (row) => {
		dialogTableVisible.value = true;
		selectValue.value = {
			title: row?.title,
			type_id: row?.type_id,
		};
		type_id.value = row?.type_id;
		listKt();
	};
	const listKt = () => {
		listKeyWordType({
			type_id: type_id.value,
		}).then((res) => {
			gridData.value = [];
			if (res.value.error === 0) {
				gridData.value = res.value.data;
			}
		});
	};
	// 删除
	const deleteKt = (id) => {
		var ids = [id];
		ElMessageBox.confirm(
			`确定对[id=${ids.join(",")}]进行[${id ? "删除" : "批量删除"}]操作?`,
			"提示",
			{
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			}
		).then(() => {
			deleteKeyWordType(ids).then(async (res) => {
				if (res.value.error === 0) {
					ElMessage.success("删除成功");
					listKt();
				} else {
					ElMessage.error("删除失败");
				}
			});
		});
	};

	const closeKt = () => {
		renderData();
	};

	const saveKt = () => {
		ktModel.keyword_type_id = keyword_type_id?.value
			? keyword_type_id.value
			: null;
		if (!selectValue?.value) {
			ElMessage.error("请选择语句分类");
		}
		ktModel.type_id = selectValue?.value.type_id;
		saveKeyWordType(ktModel).then(async (res) => {
			if (res.value.error === 0) {
				ElMessage.success("操作成功");
				listKt();
				ktModelVisible.value = false;
			} else {
				ElMessage.error("操作失败");
			}
		});
	};
</script>
<style>
	.el-tag + .el-tag {
		margin-left: 10px;
		margin-top: 5px;
	}
</style>